package com.yxdj.common.rabbit.service;

import com.alibaba.fastjson2.JSON;
import com.yxdj.common.rabbit.domain.MtyCorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 韩总
 */
public class RabbitService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    public boolean sendMessage(String exchange , String routingKey, Object message) {

        //1.创建自定义相关消息对象-包含业务数据本身，交换器名称，路由键，队列类型，延迟时间,重试次数
        MtyCorrelationData correlationData = new MtyCorrelationData();
        String uuid = "mq:" + UUID.randomUUID().toString().replaceAll("-", "");
        correlationData.setId(uuid);
        correlationData.setMessage(message);
        correlationData.setExchange(exchange);
        correlationData.setRoutingKey(routingKey);

        //注意：此处需要先存入redis，再发送消息，否则可能returnsCallback已经触发，但是redis中还没有消息，出现空指针异常
        //2.将相关消息存入Redis  Key：UUID  相关消息对象  10 分钟
        redisTemplate.opsForValue().set(uuid, JSON.toJSONString(correlationData), 10, TimeUnit.MINUTES);


        //调用RabbitTemplate中的方法发送消息
        rabbitTemplate.convertAndSend(exchange, routingKey, message,correlationData);
        return true;
    }
}
